package com.example.landlord.demo.utils.system;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.ArrayList;

public class MyWebSocketServer extends WebSocketServer {
    private int port =8081;
    static volatile UsersOperationSystem userCollection = new UsersOperationSystem();   //客户集合
    static volatile ArrayList<LandLord> landlordList;                //记录游戏列表
    public MyWebSocketServer(int port){
        super(new InetSocketAddress(port));
        landlordList=new ArrayList<LandLord>();
    }

    public LandLord getLandlordByRoomId(String roomId){
        for(LandLord l : landlordList){  //根据Id寻找房间
            if(l.id.equals(roomId)){
                return l;
            }
        }
        return null;
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        if(userCollection.removeUser(webSocket)){
            System.out.println("当前在线人数为:"+userCollection.getUsers().size());
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
//        System.out.println(webSocket.getRemoteSocketAddress()+"发送了信息:"+s);
        //解析信息
        WebSocketMessage webSocketMessage = new WebSocketMessage(s,webSocket);
        UserHandle userHandle = new UserHandle(webSocketMessage, this);
        userHandle.start();
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        if(userCollection.removeUser(webSocket)){
            System.out.println("当前在线人数为:"+userCollection.getUsers().size());
        }
    }

    @Override
    public void onStart() {

    }
}
